package com.neuedu.hisboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.hisboot.entity.User;
import com.neuedu.hisboot.mapper.UserMapper;
import com.neuedu.hisboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jaun
 * @since 2025-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User login(String username, String password) {
        // 创建 QueryWrapper 对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 设置查询条件
        queryWrapper.eq("UName", username)
                .eq("UPassword", password);
//                .eq("DelMark", 1); // 只查询未删除的用户

        // 执行查询
        return this.getOne(queryWrapper);
    }

    @Override
    public List<User> getUsersByDeptId(Integer deptId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DeptID", deptId);
        queryWrapper.eq("UseType", 172);
        List<User> list = list(queryWrapper);
        // 可以在这里进行敏感信息处理，或者返回后由Controller处理
        return list;
    }

    @Override
    public List<User> getByUserType(Integer userType) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UseType", userType);
        queryWrapper.eq("DelMark", 1);
        return this.list(queryWrapper);
    }

    @Override
    public List<User> getByDeptId(Integer deptId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DeptID", deptId);
        queryWrapper.eq("DelMark", 1);
        return this.list(queryWrapper);
    }

    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        try {
            User user = this.getById(userId);
            if (user == null) {
                return false;
            }
            
            // 验证旧密码
            if (!user.getPassword().equals(oldPassword)) {
                return false;
            }
            
            // 更新密码
            user.setPassword(newPassword);
            return this.updateById(user);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public User getByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserName", username);
        queryWrapper.eq("DelMark", 1);
        return this.getOne(queryWrapper);
    }
}
